package cn.yanghan.service.impl;

import cn.yanghan.doc.CourseDoc;
import cn.yanghan.dto.CourseSearchParamDto;
import cn.yanghan.mapper.HighlightResultMapper;
import cn.yanghan.repository.CourseElasticsearchRepository;
import cn.yanghan.service.ICourseElasticsearchService;
import cn.yanghan.utils.util.PageList;
import cn.yanghan.vo.AggPageList;
import cn.yanghan.vo.Bucket;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import javax.swing.text.Highlighter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CourseElasticsearchServiceImpl implements ICourseElasticsearchService {

    @Autowired
    private CourseElasticsearchRepository repository;

    @Autowired
    private ElasticsearchRestTemplate template;

    @Autowired
    private HighlightResultMapper highlightResultMapper;


    @Override
    public void add(CourseDoc courseDoc) {
        //调用添加方法添加ES的文档
        repository.save(courseDoc);
    }

    @Override
    public PageList<CourseDoc> searchCourse(CourseSearchParamDto dto) {

        //查询对象的建造者
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        //-----分页
        builder.withPageable(PageRequest.of(dto.getPage()-1, dto.getRows()));
        //-----排序
        if(StringUtils.isNotEmpty(dto.getSortField())){
            String sortField = "onLineTime";
            switch (dto.getSortField()){
                case "xl":sortField = "saleCount";break;
                case "xp":sortField = "onLineTime";break;
                case "jp":sortField = "price";break;
                case "rq":sortField = "viewCount";break;
                case "pl":sortField = "commentCount";break;
            }
            SortOrder sortOrder = SortOrder.DESC;
            if(StringUtils.isNotEmpty(dto.getSortType())&&
                dto.getSortType().equalsIgnoreCase("asc")){
                sortOrder = SortOrder.ASC;
            }
            builder.withSort(new FieldSortBuilder("price").order(sortOrder));
        }


        //-----查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //DSL查询
        if(StringUtils.isNotEmpty(dto.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("name",dto.getKeyword()));
        }

        //DSL过滤
        if(null!=dto.getCourseTypeId()){
            boolQueryBuilder.filter(QueryBuilders.termQuery("courseTypeId",dto.getCourseTypeId()));
        }
        if(StringUtils.isNotEmpty(dto.getGradeName())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("gradeName",dto.getGradeName()));
        }
        if(null!=dto.getPriceMin()){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(dto.getPriceMin()));
        }
        if(null!=dto.getPriceMax()){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(dto.getPriceMax()));
        }
        if(StringUtils.isNotEmpty(dto.getTenantName())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("tenantName(",dto.getTenantName()));
        }
        builder.withQuery(boolQueryBuilder);
        //处理高亮
        HighlightBuilder.Field highlightField = new HighlightBuilder.Field("name")
                .preTags("<font style='color:red'>")
                .postTags("</font>");
        builder.withHighlightFields(highlightField);
        //机构terms的聚合
        TermsAggregationBuilder tenantAgg = AggregationBuilders
                .terms("tenantAgg").field("tenantName");
        //等级聚合
        TermsAggregationBuilder gradeAgg = AggregationBuilders
                .terms("gradeAgg").field("gradeName");
        builder.addAggregation(tenantAgg).addAggregation(gradeAgg);

        //创建搜索对象
        SearchQuery searchQuery = builder.build();
        //执行搜索
        //Page<CourseDoc> page = repository.search(searchQuery);
        AggregatedPage<CourseDoc> page = template.queryForPage(searchQuery,CourseDoc.class,highlightResultMapper);
        //处理聚合结果
        Aggregations aggregations = page.getAggregations();
        Map<String, Aggregation> aggregationMap = aggregations.asMap();

        //疯转聚合结果
        Map<String, List<Bucket>> aggs = new HashMap<>();
        //循环map集合，取出key和value
        aggregationMap.entrySet().forEach(entry->{
            //聚合的名字
            String aggName = entry.getKey();

            //结果列表
            List<Bucket> bucketResult = new ArrayList<>();
            //聚合对象
            ParsedStringTerms value = (ParsedStringTerms) entry.getValue();
            List<? extends Terms.Bucket> buckets = value.getBuckets();
            buckets.forEach(bucket -> {
                String key = bucket.getKeyAsString();
                long docCount = bucket.getDocCount();
                bucketResult.add(new Bucket(key,docCount));
            });

            aggs.put(aggName,bucketResult);
        });

        //把结果封装到pageList，总页数，总条数
        return new AggPageList(page.getTotalElements(), page.getContent(),aggs);
    }
}
